package com.example.administrator.newsapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.newsapp.pojo.Data;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * ClassName:
 * Description:
 */

public class FragmentTab extends android.support.v4.app.Fragment {
    private static final int DATA_SUCCESS = 1001;
    private static final int DATA_ERROR = 1004;
    private View mContentView;//缓存视图内容
    private RecyclerView mRecyclerView;
    private List<Data.ResultBean.DataBean> listData;
    private ListAdapter mAdapter;
    private Handler handler;
    private SwipeRefreshLayout swipeRefresh;
    private TextView errorMsg;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(mContentView==null){
            mContentView=inflater.inflate(R.layout.fragment_tabs,container,false);
        }
        ViewGroup viewGroup = (ViewGroup) mContentView.getParent();
        if(viewGroup!=null){
            viewGroup.removeView(mContentView);
        }
        return mContentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        mRecyclerView=view.findViewById(R.id.recycle_view);
        initDataFromOKHttp();
        swipeRefresh = view.findViewById(R.id.swipe_fresh);
        Log.e("swipeRefresh", swipeRefresh.toString());
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initDataFromOKHttp();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                        swipeRefresh.setRefreshing(false);
                        Toast.makeText(mContentView.getContext(),"刷新完成",Toast.LENGTH_SHORT).show();
                    }
                }, 2000);
            }
        });
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what==DATA_SUCCESS){
                    listData = (List<Data.ResultBean.DataBean>) msg.obj;
                    mAdapter=new ListAdapter(getContext(),listData);
                    LinearLayoutManager layoutManager= new LinearLayoutManager(getContext());
                    mRecyclerView.setLayoutManager(layoutManager);
                    mRecyclerView.setAdapter(mAdapter);
                    mAdapter.setmOnItemClickListener(new ListAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            Intent intent = new Intent(getContext(),ContentActivity.class);
                            String url = listData.get(position).getUrl();
                            String image = listData.get(position).getThumbnail_pic_s();
                            String title = listData.get(position).getTitle();
                            intent.putExtra("URL",url);
                            intent.putExtra("IMAGE",image);
                            intent.putExtra("TITLE",title);
                            intent.putExtra("NEWID",listData.get(position).getUniquekey());
                            startActivity(intent);
                        }
                    });
                    return true;
                }
                if(msg.what==DATA_ERROR){
                    errorMsg = mContentView.findViewById(R.id.error_msg);
                    errorMsg.setVisibility(View.VISIBLE);
                    errorMsg.setText("今日请求数据次数已用完");
                }
                return false;
            }
        });
    }

    private void initDataFromOKHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                String url="http://v.juhe.cn/toutiao/index";
                RequestBody requestBody = new FormBody.Builder()
                        .add("key","61f211829fb7be9f035e8de8f57976c7")
                        .add("type",getTag())
                        .build();
                final Request request = new Request.Builder().url(url).post(requestBody).build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("FragmenTab", e.toString());
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //Log.e("FragmenTab",response.body().string());
                        try{
                            String jsonStr = response.body().string();
                            Gson gson = new Gson();
                            Data data = gson.fromJson(jsonStr,Data.class);
                            Data.ResultBean result = data.getResult();
                            List<Data.ResultBean.DataBean> listData = result.getData();
                            Message message= new Message();
                            message.what=DATA_SUCCESS;
                            message.obj = listData;
                            handler.sendMessage(message);
                        }catch (NullPointerException e){
                            Message message= new Message();
                            message.what=DATA_ERROR;
                            handler.sendMessage(message);
                            Log.e("FragmentTab_onResponse", "今日请求数据次数已用完");
                        }
                    }
                });
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
